<?php

declare(strict_types=1);
/**
 * 搜索文章
 *
 * @contact  593809624@qq.com
 * @author   刘传望
 * @date  2025-10-16
 */
namespace App\Controller\v1;

use App\Controller\AbstractController;
use App\Service\SearchService;
use Hyperf\Context\Context;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\Middleware;
//token认证中间件
#[Middleware(\App\Middleware\TokenOptionalMiddleware::class)]

#[Controller(prefix: "/api/v1/search")]
class SearchController extends AbstractController
{
    #[Inject]
    private SearchService $searchService;

    /**
     * 搜索列表接口
     * @param $q 搜索关键词
     * @param $page 页码
     * @param $size 每页数量
     * @param $sort 排序 (relevance,latest,popular)
     * @param $tags 标签筛选，多个用逗号分隔
     * @param $author 作者ID筛选
     * @return array|\Psr\Http\Message\ResponseInterface
     */
    #[GetMapping("articles")]
    public function articles(RequestInterface $request)
    {
        $userId = (int) Context::get("login_user_id");

        $size = (int) $request->input("size",20);
        $page = (int) $request->input("page",1);

        $q = $request->input("q") ?: '';
        $tags = $request->input("tags");
        $author = (int) $request->input("author");
        $sort = $request->input("sort");
        $sort = in_array($sort, ["relevance", "latest","popular"]) ? $sort : "relevance";
        $date_start = $request->input("date_start");
        $date_end = $request->input("date_end");

        $filters = [
            'sort' => $sort,
        ];

        if ($author) {
            $filters['user_id'] = $author;
        }

        if ($tags) {
            $filters['tags'] = explode(',',$tags);
        }

        if ($date_start && $date_end) {
            $filters['date_range'] = [
                'start'=>$date_start,
                'end'=>$date_end,
            ];
        }

        $data = $this->searchService->searchArticles($q,$filters,$userId,$page,$size);
        $suggestions = $this->searchService->getSuggestions($q);

        return $this->success([
            'articles'=>$data['items'],
            'pagination'=>[
                "page"=>$page,
                "size"=>$size,
                "total"=>$data['total'],
                "pages"=>ceil($data['total']/$size),
            ],
            "suggestions"=>$suggestions
        ]);
    }

    /**
     * 获取搜索建议
     * @param $limit 获取数量
     * @param $q 关键词
     * @return array|\Psr\Http\Message\ResponseInterface
     */
    #[GetMapping("suggestions")]
    public function suggestions(RequestInterface $request)
    {
        $limit = (int)$request->input("limit", 10);
        $q = $request->input("q") ?: '';

        $suggestions = $this->searchService->getSuggestions($q,$limit);

        return $this->success([
            "suggestions"=>$suggestions
        ]);
    }

    /**
     * 从 ES 获取文章详情
     * @param RequestInterface $request
     * @return array|\Psr\Http\Message\ResponseInterface
     */
    #[GetMapping("articles/{id}")]
    public function articleDetail(RequestInterface $request, int $id)
    {
        $userId = (int) Context::get("login_user_id");
        $doc = $this->searchService->getArticleFromESById($id,$userId);
        if (empty($doc)) {
            return $this->fail(404, "文章不存在", null);
        }
        return $this->success($doc, "success");
    }
}
